package com.runchamp;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentSender;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.ContextThemeWrapper;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.SignInButton;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.plus.Plus;
import com.google.android.gms.plus.model.people.Person;
import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.JsonHttpResponseHandler;
import com.loopj.android.http.RequestParams;
import com.runchamp.GoogleCloudMessagingUtils.RegisterDevice;

import org.json.JSONObject;

/* This activity is in charge of the authenticating the user */
public class Login extends Activity implements View.OnClickListener, GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener {
    private static final int RC_SIGN_IN = 9001;
    private final static String SIGNIN_URL = "http://runtobo.appspot.com/signIn";
    private static final String NICKNAME_URL = "http://runtobo.appspot.com/nickname";
    Intent intent;
    private SignInButton signinButton;
    private Button signoutBttton;
    private boolean mSignInClicked;
    private ConnectionResult mConnectionResult;
    private boolean mIntentInProgress;
    private GoogleApiClient mGoogleApiClient;
    private String nickname;
    private Button login;
    private TextView userName;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        intent = new Intent(this, MyRaces.class);
        mGoogleApiClient = new GoogleApiClient.Builder(this)
                .addConnectionCallbacks(this)
                .addOnConnectionFailedListener(this)
                .addApi(Plus.API)
                .addScope(Plus.SCOPE_PLUS_LOGIN)
                .build();

        signinButton = (SignInButton) findViewById(R.id.sign_in_button);
        signinButton.setOnClickListener(this);
        final SharedPreferences prefs = getSharedPreferences("MyPrefsFile", Context.MODE_PRIVATE);
        if (prefs.contains("userID")) {
            signinButton.setVisibility(View.INVISIBLE);
            Toast.makeText(this, "Logging in...", Toast.LENGTH_SHORT).show();
        }
    }


    @Override
    public void onClick(View view) {
        if (view.getId() == signinButton.getId()
                && !mGoogleApiClient.isConnecting()) {
            mSignInClicked = true;
            mGoogleApiClient.connect();
            resolveSignInError();
        }
    }

    private void resolveSignInError() {
        if (mConnectionResult.hasResolution()) {
            try {
                mIntentInProgress = true;
                startIntentSenderForResult(mConnectionResult.getResolution().getIntentSender(),
                        RC_SIGN_IN, null, 0, 0, 0);
            } catch (IntentSender.SendIntentException e) {
                // The intent was canceled before it was sent.  Return to the default
                // state and attempt to connect to get an updated ConnectionResult.
                mIntentInProgress = false;
                mGoogleApiClient.connect();
            }
        }
    }

    @Override
    public void onConnected(Bundle bundle) {
        mSignInClicked = false;
        final Context me = this;
        // get the user ID from DB
        if (Plus.PeopleApi.getCurrentPerson(mGoogleApiClient) != null) {

            Person currentPerson = Plus.PeopleApi.getCurrentPerson(mGoogleApiClient);
            /*String personName = currentPerson.getDisplayName();
            String personId = currentPerson.getId();
            String personGooglePlusProfile = currentPerson.getUrl();*/
            final String email = Plus.AccountApi.getAccountName(mGoogleApiClient);
            String birthday = currentPerson.getBirthday();
            AsyncHttpClient client = new AsyncHttpClient();
            RequestParams params = new RequestParams();
            params.put("email", email);
            //params.put("name", email.split("@")[0]);
            params.put("birthday", birthday);
            client.get(SIGNIN_URL, params, new JsonHttpResponseHandler() {
                @Override
                public void onSuccess(JSONObject response) {
                    final String userId = response.optString("userId");
                    String hasName = response.optString("hasName");
                    intent.putExtra("user", userId);

                    //Save ndb UserID in shared prefs
                    final SharedPreferences prefs = getSharedPreferences("MyPrefsFile", Context.MODE_PRIVATE);
                    SharedPreferences.Editor editor = prefs.edit();
                    editor.putString("userID", userId);
                    editor.putString("nickname", response.optString("nickname"));
                    editor.commit();

                    //write only in the first time the default settings for the new user - if already excist - ignore
                    String settingsFreq = prefs.getString("Settings/distanceFreq", "");
                    Log.i("prefs srettings: ", settingsFreq);
                    if (settingsFreq.equals("")) {
                        Log.i("insdie if: ", "hereee");
                        editor.putString("Settings/distanceFreq", String.valueOf(1.0));
                        editor.putString("Settings/timeFreq", String.valueOf(300));
                        editor.putString("Settings/informationIndex", String.valueOf(1));
                        editor.putString("Settings/onTouchAlerts", String.valueOf(1));
                        editor.commit();
                        settingsFreq = prefs.getString("Settings/distanceFreq", "");
                        Log.i("prefs after: ", settingsFreq);
                    }


                    RegisterDevice registerDevice = new RegisterDevice();
                    registerDevice.registerUserDevice(getApplicationContext());

                    if (hasName.equals("true"))
                        startActivity(intent);
                    else {
                        LayoutInflater inflater = getLayoutInflater();
                        View promptView = inflater.inflate(R.layout.dialog_nickname, null);
                        final AlertDialog d = new AlertDialog.Builder(Login.this)
                                .setView(promptView)
                                .setMessage("Hello! please enter a nickname:")
                                .setPositiveButton(R.string.OK, null)
                                .setNegativeButton(R.string.cancel, null)
                                .create();

                        d.setOnShowListener(new DialogInterface.OnShowListener() {
                            @Override
                            public void onShow(DialogInterface dialog) {
                                final TextView errorTextView = (TextView) d.findViewById(R.id.nicknameError);
                                final EditText nicknameText = (EditText) d.findViewById(R.id.nickname);
                                nicknameText.addTextChangedListener(new TextWatcher() {
                                    @Override
                                    public void beforeTextChanged(CharSequence s, int start, int count, int after) {
                                    }

                                    @Override
                                    public void onTextChanged(CharSequence s, int start, int before, int count) {
                                        errorTextView.setText("");
                                    }

                                    @Override
                                    public void afterTextChanged(Editable s) {
                                    }
                                });

                                nicknameText.setText(email.split("@")[0]);
                                Button buttonOK = d.getButton(AlertDialog.BUTTON_POSITIVE);
                                Button buttonCancel = d.getButton(AlertDialog.BUTTON_NEGATIVE);
                                buttonOK.setOnClickListener(new View.OnClickListener() {
                                    @Override
                                    public void onClick(View view) {
                                        errorTextView.setTextColor(Color.BLACK);
                                        errorTextView.setText("Verifying nickname...");
                                        RequestParams params = new RequestParams();
                                        params.add("userId", userId);
                                        nickname = String.valueOf(nicknameText.getText());
                                        params.add("nickname", nickname);
                                        AsyncHttpClient client = new AsyncHttpClient();
                                        client.post(NICKNAME_URL, params, new JsonHttpResponseHandler() {
                                            @Override
                                            public void onSuccess(JSONObject response) {
                                                String success = response.optString("success");
                                                if (success.equals("failed")) {
                                                    errorTextView.setTextColor(Color.red(0));
                                                    errorTextView.setText("Nickname is not available");
                                                } else {
                                                    d.dismiss();
                                                    final SharedPreferences prefs = getSharedPreferences("MyPrefsFile", Context.MODE_PRIVATE);
                                                    SharedPreferences.Editor editor = prefs.edit();
                                                    editor.putString("nickname", nickname);
                                                    editor.commit();

                                                    startActivity(intent);
                                                }
                                            }

                                            @Override
                                            public void onFailure(Throwable e, JSONObject errorResponse) {
                                                String x = "";
                                            }
                                        });
                                    }
                                });
                                buttonCancel.setOnClickListener(new View.OnClickListener() {
                                    @Override
                                    public void onClick(View v) {
                                        d.dismiss();
                                        startActivity(intent);
                                    }
                                });

                            }
                        });
                        d.show();
                    }
                }

                @Override
                public void onFailure(Throwable e, JSONObject errorResponse) {
                    super.onFailure(e, errorResponse);
                }
            });
            Toast.makeText(this, "Unable to connect", Toast.LENGTH_SHORT);
        }
    }

    @Override
    public void onConnectionSuspended(int i) {
    }

    @Override
    public void onConnectionFailed(ConnectionResult result) {
        if (!mIntentInProgress) {
            // Store the ConnectionResult so that we can use it later when the user clicks
            // 'sign-in'.
            mConnectionResult = result;

            if (mSignInClicked) {
                // The user has already clicked 'sign-in' so we attempt to resolve all
                // errors until the user is signed in, or they cancel.
                resolveSignInError();
            }
        }
    }

    @Override
    protected void onStart() {
        super.onStart();
        mGoogleApiClient.connect();
    }

    protected void onStop() {
        super.onStop();
        if (mGoogleApiClient.isConnected()) {
            mGoogleApiClient.disconnect();
        }
    }

    protected void onActivityResult(int requestCode, int responseCode, Intent intent) {
        if (requestCode == RC_SIGN_IN) {
            if (responseCode != RESULT_OK) {
                mSignInClicked = false;
            }

            mIntentInProgress = false;

            if (!mGoogleApiClient.isConnecting()) {
                mGoogleApiClient.connect();
            }
        }
    }
}

